import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';

export async function DELETE(req: NextRequest, { params }: { params: { groupId: string } }) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { groupId } = params;

    // 1. 检查群组是否存在
    const group = await prisma.group.findUnique({
      where: { id: groupId },
    });

    if (!group) {
      return NextResponse.json({ error: '群组不存在' }, { status: 404 });
    }

    // 2. 禁止群主退出群组
    if (group.ownerId === userId) {
      return NextResponse.json({ error: '群主不能退出群组，请先转让群主' }, { status: 400 });
    }

    // 3. 验证用户是否是群成员
    const membership = await prisma.groupMember.findUnique({
        where: {
            groupId_userId: {
                groupId,
                userId,
            },
        },
    });

    if (!membership) {
        return NextResponse.json({ error: '你不是该群组成员' }, { status: 404 });
    }

    // 4. 删除成员记录
    await prisma.groupMember.delete({
      where: {
        id: membership.id,
      },
    });

    return NextResponse.json({ message: '已成功退出群组' });
  } catch (error) {
    console.error('退出群组失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 